package com.basiclib.network

import com.basiclib.utils.L
import io.reactivex.Observable
import io.reactivex.ObservableSource
import io.reactivex.functions.Function
import java.util.concurrent.TimeUnit


class RetryWithDelay(var maxRetries: Int = 3, var retryDelaySecond: Int = 2) :
    Function<Observable<Throwable>, ObservableSource<*>> {


    val TAG = this.javaClass.simpleName
    private var retryCount: Int = 0

    override fun apply(t: Observable<Throwable>): ObservableSource<*> {
        return t.flatMap(object : Function<Throwable, ObservableSource<*>> {

            override fun apply(throwable: Throwable): ObservableSource<*> {
                if (++retryCount <= maxRetries) {
                    // When this Observable calls onNext, the original Observable will be retried (i.e. re-subscribed).

                    L.d(
                        TAG, "Observable get error, it will try after " + retryDelaySecond
                                + " second, retry count " + retryCount
                    )

                    return Observable.timer(retryDelaySecond.toLong(), TimeUnit.SECONDS)
                }
                return Observable.error<Any>(throwable)
            }

        })
    }

}